{% extends 'base.html' %}
{% load staticfiles %}
{% load custom_tags %}

{% block head %}
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/awesome-bootstrap-checkbox.css' %}">
    <link rel="stylesheet" href="{% static 'css/dataTables.checkboxes.css' %}">
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'modaal/css/modaal.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/selectize.css' %}">
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/toastr.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/bootstrap-editable.css' %}">
    <style>
        /* dataTables列内容居中 */
        #example1 > tbody > tr > td {
            text-align: center;
            word-wrap: break-word;
        }

        /* dataTables表头居中 */
        #example1 > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        #buttonBar button {
            margin-right: 2px;
            margin-bottom: 5px;
        }

        #searchBox .form-group > label {
            margin-top: 5px; text-align: right; padding-right: 0px; padding-left: 0px;
        }

        #searchBox .form-group > .input-group {
            position: relative;
            left: 15px;
        }

        #updatePWDModal .modal-body, #importAssetsModal .modal-body {
            margin-bottom: 10px;
        }

        .toast-vertical-center {
            top:10%;
            left:30%;
        }

        #toast-container>div {
            padding-top: 23px;
        }

        #example1_filter>label>input {
            width: 200px;
        }

        .selectize-dropdown.plugin-optgroup_columns .optgroup {
            width: 100% !important;
            height: inherit !important;
            border-right: 1px solid #f2f2f2;
            border-top: 0 none;
            float: left;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
        }

        .selectize-dropdown.plugin-optgroup_columns .optgroup .option {
            margin-left: 5px;
        }

        .selectize-dropdown.plugin-optgroup_columns .optgroup-header {
            font-weight: bold;
            color: #303030;
            background: #fff;
            cursor: default;
            border-top: 0 none;
        }

    </style>

{% endblock %}

{% block content %}

    <div class="row" style="overflow-x: auto;">
        <div class="col-xs-12 col-lg-8 pull-left" id="buttonBar" style="margin-bottom: 3px;">
            {% if perms.assets.add_assets %}
            <a href="{% url 'add_asset' %}">
                <button class="btn btn-sm btn-success pull-left">
                    <i class="fa fa-plus-square"></i>
                    <span class="bigger-110">新增资产</span>
                </button>
            </a>
            {% endif %}
            {% if perms.assets.add_assets %}
            <button class="btn btn-sm btn-info pull-left" data-toggle="modal" data-target="#importAssetsModal" onclick="document.getElementById('import_assets_info').reset();">
                <i class="fa fa-upload"></i>
                <span class="bigger-110">批量导入</span>
            </button>
            {% endif %}
            <div class="btn-group pull-left">
                <button type="button" class="btn btn-primary btn-sm" style="margin-right: 0;">批量导出</button>
                <button type="button" class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu dropdown-menu-left" role="menu">
                    <li>
                        <a type="button" class="btn pull-left" id="exportChecked">
                            <i class="fa fa-file-text"></i>
                            <span class="bigger-110">导出勾选的资产</span>
                        </a>
                    </li>
                    {% if user.is_superuser %}
                    <li><a type="button" class="btn pull-left" id="downloadServerAssets"><i class="fa fa-download"></i>导出检索的服务器资产</a></li>
                    <li><a type="button" class="btn pull-left" id="downloadSelectedServerAssets"><i class="fa fa-download"></i>导出勾选的服务器资产</a></li>
                    {% endif %}
                </ul>
            </div>
            {% if perms.assets.delete_assets %}
            <button class="btn btn-sm btn-danger pull-left" id="deleteChecked">
                <i class="fa fa-exclamation-triangle"></i>
                <span class="bigger-110">批量删除</span>
            </button>
            {% endif %}
            <button class="btn btn-sm btn-info pull-left" style="display: none;" id="refreshCondition">
                <i class="glyphicon glyphicon-trash"></i>
                <span class="bigger-110">清空筛选</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" id="advancedSearchBox">
                <i class="fa fa-search"></i>
                <span class="bigger-110">高级筛选</span>
            </button>
            <button class="btn btn-sm btn-info pull-left" style="display: none;" id="advancedSearch">
                <i class="fa fa-search"></i>
                <span class="bigger-110">点击筛选</span>
            </button>
        </div>
        <form id="searchForm">
            <div id="searchBox" style="width: 99%; display: none;">
                <div class="clearfix visible-xs"></div>
                <div class="col-md-12 col-lg-12 col-xs-12 pull-left" style="margin: 3px 3px 6px 3px;">
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_nu" class="col-lg-4 col-md-4 col-xs-3 control-label">资产名称</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="asset_nu" name="asset_nu">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_management_ip" class="col-lg-3 col-md-4 col-xs-3 control-label">管理IP</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <input type="text" class="form-control" id="asset_management_ip" name="asset_management_ip">
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_environment" class="col-lg-3 col-md-4 col-xs-3 control-label">设备环境</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                              <select class="form-control" id="asset_environment" style="width: 100%;" name="asset_environment">
                                    <option value=""></option>
                                    {% for choice in environment_choice_ %}
                                        <option value="{{ choice.0 }}">{{ choice.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_type" class="col-lg-4 col-md-4 col-xs-3 control-label">资产类型</label>
                            <div class="col-lg-8 col-md-8 col-xs-9">
    {#                          <input type="text" class="form-control" id="asset_type">#}
                                <select class="form-control" id="asset_type" style="width: 100%;" name="asset_type">
                                        <option value=""></option>
                                    {% for type in asset_types %}
                                        <option value="{{ type.0 }}">{{ type.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_status" class="col-lg-3 col-md-4 col-xs-3 control-label">设备状态</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                                <select class="form-control" id="asset_status" style="width: 100%;" name="asset_status">
                                        <option value=""></option>
                                    {% for status in asset_status_ %}
                                        <option value="{{ status.0 }}">{{ status.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_status" class="col-lg-3 col-md-4 col-xs-3 control-label">使用期限</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                                <select class="form-control" id=is_expired style="width: 100%;" name="is_expired">
                                    <option value=""></option>
                                    {% for status in is_expired_ %}
                                        <option value="{{ status.0 }}">{{ status.1 }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                     <div class="form-group" style="margin-bottom: 0;">
                         <label class="control-label col-lg-4 col-md-4 col-xs-3">申请时间</label>
                         <div class="input-group col-lg-8 col-md-8 col-xs-9">
                            <input type="text" class="form-control" name="asset_purchase_day_start" id="asset_purchase_day_start" placeholder="开始时间"/>
                            <span class="input-group-addon">to</span>
                            <input type="text" class="form-control" name="asset_purchase_day_end" id="asset_purchase_day_end" placeholder="结束时间"/>
                         </div>
                     </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                     <div class="form-group" style="margin-bottom: 0;">
                         <label class="control-label col-lg-3 col-md-4 col-xs-3">到期时间</label>
                         <div class="input-group col-lg-9 col-md-8 col-xs-9">
                            <input type="text" class="form-control" name="asset_expire_day_start" id="asset_expire_day_start" placeholder="开始时间"/>
                            <span class="input-group-addon">to</span>
                            <input type="text" class="form-control" name="asset_expire_day_end" id="asset_expire_day_end" placeholder="结束时间"/>
                         </div>
                     </div>
                    </div>
                    <div class="col-md-6 col-lg-4 col-xs-12" style="margin: 3px 0;">
                        <div class="form-group">
                            <label for="asset_product" class="col-lg-3 col-md-4 col-xs-3 control-label">产品名称</label>
                            <div class="col-lg-9 col-md-8 col-xs-9">
                                <select id="asset_product" style="display: none;" name="asset_product"></select>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="clearfix visible-xs"></div>
            </div>
        </form>

        <div class="modal fade" id="importAssetsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
             aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Excel文件批量导入资产</h4>
                    </div>
                    {% if perms.assets.add_assets %}
                        <div class="modal-body" style="margin-bottom: -10px;">
                            <div class="form-horizontal">
                                <div class="col-sm-12" style="line-height: 10px; margin-bottom: 10px;">注意：只支持导入IP地址未被占用的服务器资产！</div>
                                <div class="form-group">
                                    <label class="col-sm-2 control-label">导入模板</label>
                                    <div class="col-sm-6" style="margin-top: 3px;">
                                        <button type="button" class="btn btn-info btn-sm" onclick="window.location.href='/assets/download_assets_template'">下载<i class="fa fa-fw fa-download"></i></button></a>
                                    </div>
                                </div>
                                <form id="import_assets_info">
                                    <div class="form-group">
                                        <label class="col-sm-2 control-label">上传文件</label>
                                        <div class="col-sm-6" style="margin-top: 3px;">
                                            <input type="file" name="import_file" placeholder="上传excel文件" id="import_file"
                                                   accept=".csv,.xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"/>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="import_assets()">导入</button>
                        </div>
                    {% else %}
                        <div class="modal-body">
                            抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!--dataTable-->
        <div class="col-xs-12">
            <!-- /.box -->
            <div class="box" style="min-width: 1100px;">
                <div class="box-body">
                    <table id="example1" class="table table-bordered table-striped" style="width:100%; table-layout: fixed;">
                        <thead>
                            <tr>
                                <th></th>
                                <th>序号</th>
                                <th>资产类型</th>
                                <th>资产名称</th>
                                <th>管理IP</th>
                                <th>产品名称</th>
                                <th>使用期限</th>
                                <th>设备状态</th>
                                <th>备注</th>
                                {% if perms.assets.change_assets or perms.assets.change_serverassets or perms.assets.delete_assets %}
                                <th>操作</th>
                                {% endif %}
                            </tr>
                        </thead>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
    </div>
    <!-- /.row -->
{% endblock %}


{% block js %}
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>
    <!-- iCheck 1.0.1 -->
    <script src="{% static 'js/dataTables.checkboxes.min.js' %}"></script>
    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'modaal/js/modaal.min.js' %}"></script>
    <script src="{% static 'js/selectize.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'js/bootbox.js' %}"></script>
    <script src="{% static 'js/toastr.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-editable.min.js' %}"></script>
    <script src="{% static 'js/lodash.min.js' %}"></script>
    <script src="{% static 'js/jquery.inputmask.bundle.js' %}"></script>
    <script>
        $(function () {
            $('#asset_product').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: 'text',
                load: function(query, callback) {
                    $.ajax({
                        url: '/project/find_product_name/',
                        data: {
                            product_name: query
                        },
                        dataType: 'json',
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });

            var table = $('#example1').DataTable({
                language: {
                   "sProcessing": "处理中...",
                   "sLengthMenu": "显示 _MENU_ 项结果",
                   "sZeroRecords": "没有匹配结果",
                   "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                   "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                   "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                   "sInfoPostFix": "",
                   "sSearch": "快速搜索:",
                   "searchPlaceholder": "资产编号/资产名称 管理IP 产品名称",
                   "sUrl": "",
                   "sEmptyTable": "表中数据为空",
                   "sLoadingRecords": "载入中...",
                   "sInfoThousands": ",",
                   "oPaginate": {
                       "sFirst": "首页",
                       "sPrevious": "上页",
                       "sNext": "下页",
                       "sLast": "末页"
                   },
                   "oAria": {
                       "sSortAscending": ": 以升序排列此列",
                       "sSortDescending": ": 以降序排列此列"
                   }
               },
                columnDefs: [
                    {
                        'targets': -1,
                        'orderable': false
                    },
                    {
                        'targets': 0,
                        'render': function (data, type, row, meta) {
                            if (type === 'display') {
                                data = '<div class="checkbox"><input type="checkbox" class="dt-checkboxes" value="'+row.id+'"><label></label></div>';
                            }

                            return data;
                        },
                        'checkboxes': {
                            'selectRow': true,
                        }
                    },
                    {
                        'targets': 2,
                        'render': function (data, type, row, meta) {
                            data = '<a href="/assets/get_server_info/'+row.id+'/" class="modaal-ajax-asset" data-id="'+row.id+'">'+row.type_detail[1]+'</a>'
                            return data;
                        },
                    },
                    {
                        'targets': 4,
                        'render': function (data, type, row, meta) {
                            if(row.asset_management_ip){
                                data = '<ul class="list-unstyled" style="text-align: left"><li><span class="label label-default">内</span>:'+row.asset_management_ip.IP+"</li><li>\n"
                                if(row.hosted_on){
                                    data += "<span class=\"label label-info\">外</span>:"+row.hosted_on+"</li>"
                                }
                                data += "</ul>"
                            }
                            return data;
                        },
                    },
                    {
                        'targets': 5,
                        'render': function (data, type, row, meta) {
                            return row.asset_product
                        },
                    },
                    {
                        'targets': 6,
                        'render': function (data, type, row, meta) {
                            if(row.is_expired[0]==1){
                                data = '<span class="label label-danger">'+row.is_expired[1]+'</span>'
                            } else {
                                data = '<span class="label label-success">'+row.is_expired[1]+'</span>'
                            }
                            return data;
                        },
                    },
                    {
                        'targets': 7,
                        'render': function (data, type, row, meta) {
                            if(row.asset_status[0] == 0){
                                data = '<span class="label label-success">'+row.asset_status[1]+'</span>'
                            } else if(row.asset_status[0] == 1){
                                data = '<span class="label label-danger">'+row.asset_status[1]+'</span>'
                            } else if(row.asset_status[0] == 2){
                                data = '<span class="label label-warning">'+row.asset_status[1]+'</span>'
                            } else if(row.asset_status[0] == 3){
                                data = '<span class="label label-info">'+row.asset_status[1]+'</span>'
                            }
                            return data;
                        },
                    },
                    {
                        'targets': 8,
                        'render': function (data, type, row, meta) {
                            return {% if perms.fort.ssh_fortserver %}row.asset_memo{% else %}''{% endif %}
                        },
                        'orderable': false
                    },
                    {% if perms.assets.change_assets or perms.assets.change_serverassets or perms.assets.delete_assets %}
                    {
                        'targets': 9,
                        'render': function (data, type, row, meta) {
                            data = ''
                            {% if perms.assets.change_assets %}
                            data += '<a href="/assets/update_asset/'+row.asset_type+'/'+row.id+'/"><button type="button" class="btn btn-success btn-xs">更新</button></a>\n'
                            if(row.asset_type == 'server'){
                                data += '<div class="btn-group">\n' +
                                '<button type="button" class="btn btn-primary btn-xs">收集</button>\n' +
                                '<button type="button" class="btn btn-primary btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">\n' +
                                '<span class="caret"></span>\n' +
                                '<span class="sr-only">Toggle Dropdown</span>\n' +
                                '</button>\n' +
                                '<ul class="dropdown-menu" role="menu">\n'
                                if(row.is_ssh == 1){
                                    data += '<li><a href="javascript:void(0)" onclick="serverConnect('+row.serverassets+','+row.has_username+',\'info\','+row.is_ssh+');">自动收集主体信息</a></li>\n'
                                    //data += '<li><a href="javascript:void(0)" onclick="collectInfo('+row.serverassets+', \'setup\')">自动收集主体信息</a></li>\n'
                                }
                                if(row.type_detail != 2 && row.is_ssh == 1){
                                    data += '<li><a href="javascript:void(0)" onclick="serverConnect('+row.serverassets+','+row.has_username+',\'mem\','+row.is_ssh+');">自动收集内存信息</a></li>\n'
                                    //data += '<li><a href="javascript:void(0)" onclick="collectMem('+row.serverassets+', \'get_mem\')">自动收集内存信息</a></li>\n'
                                }
                                {% if perms.assets.change_serverassets %}
                                data += '<li><a href="/assets/edit_server_info/'+row.id+'/" class="modaal-ajax-edit-asset" data-id="'+row.id+'">编辑配置信息</a></li>\n'
                                data += '</ul></div>\n'
                            }
                                {% if perms.fort.ssh_fortserver %}
                                if(row.asset_type == 'server' ){
                                    data += '<button type="button" class="btn btn-info btn-xs" onclick="serverConnect('+row.serverassets+','+row.has_username+',\'connect\');"><i class="fa fa-fw fa-terminal"></i></button></a>\n'
                                    /*if(row.is_ssh == 1){//需要改动
                                        data += '<a href="/assets/ssh/'+row.serverassets+'/" target="_blank">\n' +
                                        '<button type="button" class="btn btn-info btn-xs"><i class="fa fa-fw fa-terminal"></i></button></a>\n'
                                    } else {
                                        data += '<a href="/assets/guacamole/'+row.serverassets+'/" target="_blank">\n' +
                                        '<button type="button" class="btn btn-info btn-xs"><i class="fa fa-fw fa-terminal"></i></button></a>\n'
                                    }*/
                                }
                                {% endif %}
                                {% endif %}
                            {% endif %}
                            {% if perms.assets.delete_assets %}
                            data += '<button type="button" class="btn btn-danger btn-xs delete" data-id="'+row.id+'">删除</button>'
                            {% endif %}
                            return data;
                        },
                    }
                    {% endif %}
                ],
                "infoCallback": function(settings,start,end,max,total,pre) {
                    tableDeleteAssets()
                    serverModaal()
                    serverEditModaal()
                    var api = this.api();
                    var pageInfo = api.page.info();
                    return "共"+pageInfo.pages +"页,当前显示"+ start + "到" + end + "条记录" + ",共有"+ total + "条记录";
                },
                'select': 'multi',
                "order": [[1, "desc"]],
                "processing": true,
                "serverSide": true,
                "ajax": function (data, callback, settings) {
                    //console.log(data)
                    //封装请求参数
                    var param = {};
                    param.page_size = data.length;//页面显示记录条数，在页面显示每页显示多少项的时候
                    param.start = data.start;//开始的记录序号
                    param.page = (data.start / data.length)+1;//当前页码
                    param.search = data.search.value;
                    var order = data.order[0]
                    var order_key = data.columns[order.column].data
                    $("#searchForm").serializeArray().forEach(function(el){
                        param[el['name']]= el['value']
                    })
                    if(order.dir=="asc"){
                        param.ordering = order_key
                    } else {
                        param.ordering = '-'+order_key
                    }
                    //ajax请求数据
                    $.ajax({
                        type: "GET",
                        url: "/api/assetslist/",
                        cache: false,  //禁用缓存
                        data: param,  //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //console.log(result);
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.results;//返回的数据列表
                            //console.log(returnData);
                            callback(returnData);
                        }
                    });
                },
                columns: [
                    { "data": "id" ,"width": "50px"},
                    { "data": "id" ,"width": "50px"},
                    { "data": "asset_type" },
                    { "data": "asset_nu" },
                    { "data": "asset_management_ip" ,"width": "15%"},
                    { "data": "asset_product" },
                    { "data": "is_expired",},
                    { "data": "asset_status",},
                    { "data": "asset_memo" ,"width": "20%"},
                    {% if perms.assets.change_assets or perms.assets.change_serverassets or perms.assets.delete_assets %}{ "width": "200px",},{% endif %}
                ],
            });

            {% if user.is_superuser %}
            $("#downloadServerAssets").click(function () {
                var data = table.ajax.params();
                param={}
                param.search = data.search.value;
                var order = data.order[0]
                var order_key = data.columns[order.column].data
                $("#searchForm").serializeArray().forEach(function(el){
                    param[el['name']]= el['value']
                })
                if(order.dir=="asc"){
                    param.ordering = order_key
                } else {
                    param.ordering = '-'+order_key
                }
                param.asset_type = 'server'
                downloadServerFile("/api/export/server-assets/", $.param(param), '资产列表.xlsx')
                $.alert({
                    title: 'Tips',
                    type: 'green',
                    content: '只会导出检索的所有服务器资产（含账户/密码，且不分页）！',
                })
            })

            $("#downloadSelectedServerAssets").click(function () {
                var checkedID = checked()
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择要导出的服务器资产！',
                    })
                    return
                }
                var data = table.ajax.params();
                param={}
                var order = data.order[0]
                var order_key = data.columns[order.column].data
                if(order.dir=="asc"){
                    param.ordering = order_key
                } else {
                    param.ordering = '-'+order_key
                }
                var ids = JSON.stringify(checkedID)
                param.ids = ids
                param.asset_type = 'server'
                downloadServerFile("/api/export/server-assets/", $.param(param), '资产列表.xlsx')
                $.alert({
                    title: 'Tips',
                    type: 'green',
                    content: '只会导出勾选的服务器资产（含账户/密码）！',
                })
            })
            {% endif %}

            var dateInit = {
                format: "yyyy-mm-dd",
                clearBtn: true,
                language: "zh-CN",
                autoclose: true,
                todayHighlight: true,
            }

            $('#asset_purchase_day_start').datepicker(dateInit)
            $('#asset_purchase_day_end').datepicker(dateInit)
            $('#asset_expire_day_start').datepicker(dateInit)
            $('#asset_expire_day_end').datepicker(dateInit)

            $("#refreshCondition").click(function () {
                $("#searchBox input,#searchBox select").val("")
                $('#asset_product').selectize()[0].selectize.clear()
            })

            $("#advancedSearchBox").click(function () {
                $("#refreshCondition").show()
                $("#advancedSearchBox").hide()
                $("#advancedSearch").show()
                $("#searchBox").show()
                toastr.info("使用SHIFT+回车键开启快捷筛选。")
            });

            function tableFilter(){
                var asset_purchase_day_start = $('#asset_purchase_day_start').val()
                var asset_purchase_day_end = $('#asset_purchase_day_end').val()
                var asset_expire_day_start = $('#asset_expire_day_start').val()
                var asset_expire_day_end = $('#asset_expire_day_end').val()
                if(asset_purchase_day_start&&asset_purchase_day_end&&(asset_purchase_day_start>asset_purchase_day_end)){
                    $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '申请时间的 开始时间不能早于结束时间',
                        });
                } else if (asset_expire_day_start&&asset_expire_day_end&&(asset_expire_day_start>asset_expire_day_end)){
                    $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '到期时间的 开始时间不能早于结束时间',
                        });
                } else if (asset_purchase_day_start&&asset_expire_day_end&&(asset_purchase_day_start>asset_expire_day_end)){
                    $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '到期时间 不能早于 申请时间',
                        });
                } else {
                    table.draw(true);
                }
            }

            $("#advancedSearch").click(function () {
                tableFilter()
            });

            $(document).keypress(function (e) {
                if(e.shiftKey&&e.keyCode==13){
                    tableFilter()
                }
            })
        });

        toastr.options = {
            "closeButton": true, //是否显示关闭按钮
            "positionClass": "toast-vertical-center",//弹出窗的位置
                        }

        // Initialize Select2 Elements
        $(function () {
            $('.select2').select2()
        });

        function serverModaal(){
           // 查看服务器详细
            $('.modaal-ajax-asset').modaal({
                type: 'ajax',
                width: 1500
            });
        }

        function serverEditModaal(){
           // 查看服务器详细
            $('.modaal-ajax-edit-asset').modaal({
                type: 'ajax',
                width: 1500
            });
        }

        function checked() {
            let checkedID = [];
            var table = $('#example1').DataTable()
            {#let rows_selected = table.column(0).checkboxes.selected();#}
            var rows = $('#example1 tbody>tr>td>div>input[type=checkbox]')
            /*$.each(rows_selected, function (index, rowId) {
                checkedID.push(rowId)
            });*/
            $.each(rows, function (index, row) {
                if(row.checked == true){
                   checkedID.push(row.value)
                }
            })
            return checkedID;
        }

        // 删除资产
        function tableDeleteAssets(){
            $('#example1 tbody').off('click').on('click', '.delete', function () {
            {% if perms.assets.delete_assets %}
                let pk = $(this).attr('data-id');
                let tr_obj = $(this).parents('tr');
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/assets/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    var table = $('#example1').DataTable()
                                    table.row(tr_obj).remove().draw();
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });
        }

        // 批量删除
        $("#deleteChecked").click(function () {
            {% if perms.assets.delete_assets %}
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择要删除的资产！',
                    })
                } else {
                    $.confirm({
                        title: 'Tips',
                        content: '确定要删除这些资产么？',
                        type: 'red',
                        buttons: {
                            Ok: function () {
                                for (let i = 0; i < checkedID.length; i++) {
                                    $.ajax({
                                        url: '/api/assets/' + checkedID[i] + '/',
                                        method: 'DELETE',
                                        error: function (data) {
                                            $.alert({
                                                title: 'Tips',
                                                type: 'red',
                                                content: '删除失败！' + data.responseText,
                                            })
                                        }
                                    })
                                }
                                $.confirm({
                                    title: 'Tips',
                                    content: '删除完成！',
                                    type: 'green',
                                    buttons: {
                                        Ok: function () {
                                            window.location.reload()
                                        },
                                    }
                                })
                            },
                            Cancel: function () {
                                // close
                            }
                        }
                    })
                }
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 批量导出
        $('#exportChecked').click(function () {
            {% if perms.assets.view_assets %}
                let checkedID = checked();
                if (checkedID.length === 0) {
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: '请选择要导出的资产！',
                    })
                } else {
                    downloadServerFile('{% url 'export_assets' %}', 'pks=' + JSON.stringify(checkedID), '资产列表.xls')
                }
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有导出资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 收集主体信息
        function collectInfo(pk, module, username) {
            let data = {
                pk: pk,
                module: module,
                username: username
            };
            {% if perms.assets.add_serverassets and perms.assets.add_networkcardassets %}
                $.ajax({
                    url: "{% url 'server_facts' %}",
                    type: "POST",
                    data: data,
                    success: function (res) {
                        if (res.code === 200) {
                            $.alert({
                                title: 'Tips',
                                type: 'green',
                                content: res.msg,
                            })
                        } else {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: res.msg,
                            })
                        }
                    },
                    error: function (response) {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '自动收集失败，请自行编辑配置信息！',
                        })
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有更新资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        }

        // 收集内存信息
        function collectMem(pk, module, username) {
            let data = {
                pk: pk,
                module: module,
                username: username
            };
            {% if perms.assets.add_ramassets %}
                $.ajax({
                    url: "{% url 'server_facts' %}",
                    type: "POST",
                    data: data,
                    success: function (res) {
                        $.alert({
                            title: 'Tips',
                            type: 'green',
                            content: res.msg,
                        })
                    },
                    error: function (response) {
                        $.alert({
                            title: 'Tips',
                            type: 'red',
                            content: '自动收集失败，请自行编辑配置信息！',
                        })
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有更新资产的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        }

        // 导入资产
        function import_assets() {
            let formData = new FormData();
            let formFile = $('#import_file')[0].files[0]
            if(!formFile){
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: "请选择待上传的文件！",
                });
                return
            }
            formData.append('file', formFile);
            $.ajax({
                url: '/assets/import_assets/',
                type: 'POST',
                data: formData,
                // 告诉jQuery不要去处理发送的数据
                processData: false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType: false,
                success: function (responseStr) {
                    $.confirm({
                        title: 'Tips!',
                        content: responseStr.msg,
                        buttons: {
                            ok: function () {
                                window.location.reload();
                            },
                        }
                    });
                },
                error: function (responseStr) {
                    document.getElementById('import_assets_info').reset();
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: responseStr.responseJSON.msg,
                    });
                }
            });
        }

        var userMessage = '<select id="asset_username" style="display: none;" name="asset_username" placeholder="请选择用户"></select>'
        function usernameSelect(serverassets, is_ssh){
           $('#asset_username').selectize({
                valueField: 'id',
                labelField: 'text',
                searchField: ['text'],
                optgroups: [
                    {id: 'ssh', name: 'ssh'},
                    {id: 'telnet', name: 'telnet'},
                    {id: 'rdp', name: 'rdp'},
                ],
                optgroupField: 'protocol',
                optgroupLabelField: 'name',
                optgroupValueField: 'id',
                optgroupOrder: ['ssh', 'telnet', 'rdp'],
                preload: true,
                plugins: ['optgroup_columns'],
                load: function(query, callback) {
                    $.ajax({
                        url: '/fort/find_username',
                        dataType: 'json',
                        data: {serverassets: serverassets, is_ssh: is_ssh||0},
                        type: 'GET',
                        error: function() {
                            callback();
                        },
                        success: function(res) {
                            callback(res.results);
                        }
                    });
                }
            });
        }
        function serverConnect(serverassets, has_username, flag, is_ssh) {
            if(has_username==1){
                bootbox.dialog({
                    title: '远程连接',
                    message: userMessage,
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        ok: {
                            label: '确认',
                            className: 'btn-primary',
                            callback: function(){
                                let fort_user_id = $('#asset_username').val()
                                if(fort_user_id.length==0){
                                    toastr.error("请选择用户！")
                                    return false
                                }
                                let protocal = $('#asset_username')[0].selectize.getOption(fort_user_id).siblings().first().text()
                                let username = $('#asset_username').text()
                                if(flag=='connect'){
                                    switch(protocal){
                                        /*case 'ssh':
                                            window.open("/assets/ssh/"+fort_user_id+"/")
                                            break
                                        case 'telnet':
                                            window.open("/assets/telnet/"+fort_user_id+"/")
                                            break*/
                                        case 'vnc':
                                            $.alert({
                                                title: 'Tips',
                                                type: 'red',
                                                content: "目前暂不支持VNC远程连接。",
                                            })
                                            break
                                        default:
                                            window.open("/fort/terminal/"+fort_user_id+"/")
                                            break
                                        /*case 'rdp':
                                            window.open("/assets/guacamole/"+fort_user_id+"/")
                                            break*/
                                    }
                                } else if(flag=='info'){
                                    collectInfo(fort_user_id, 'setup', username)
                                } else if(flag=='mem'){
                                    collectMem(fort_user_id, 'get_mem', username)
                                }
                            }
                        },
                        cancel: {
                            label: '关闭',
                            className: 'btn-danger',
                        },
                    }
                })
            } else {
                {% if perms.fort.add_fortserver and perms.fort.add_fortserveruser %}
                bootbox.confirm({
                    size: "small",
                    message: "没有指定用户，请前往添加。",
                    onEscape: true,
                    backdrop: true,
                    buttons: {
                        confirm: {
                            label: '前往',
                            className: 'btn-success'
                        },
                        cancel: {
                            label: '取消',
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if(result==true){
                            location.href='/fort/fast_add_connect/'+serverassets+'/'
                        }
                    }
                })
                {% else %}
                    bootbox.alert({
                        size: "small",
                        message: "没有指定用户，请联系管理员。",
                        onEscape: true,
                        backdrop: true,
                        buttons: {
                            ok: {
                                label: '取消',
                                className: 'btn-danger'
                            }
                        }
                    })
                {% endif %}
            }
            usernameSelect(serverassets, is_ssh)
        }

        function downloadServerFile(url, param, filename){
            let xhr = new XMLHttpRequest();
            xhr.open('POST', url+"?"+param);
            xhr.responseType = 'blob';
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}');
            xhr.onload = function () {
                if (this.status === 200) {
                    let blob = this.response;
                    let reader = new FileReader();
                    reader.readAsDataURL(blob);
                    reader.onload = function (e) {
                        let a = document.createElement('a');
                        a.download = filename;
                        a.href = e.target.result;
                        a.click();
                        $(a).remove();
                    }
                }
            };
            xhr.send(param)
        }
    </script>

{% endblock %}